package com.e3.toolkit;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

public class MessageMeta {

	private Properties props;
	
	private String prefix;
	
	private String type;
	
	public MessageMeta(Properties props){
		this.props = props;
	}

	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}
	
	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix+"_";
	}
	
	public String getType() {
		return props.getProperty("type");
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getValue(String key){
		return getProps().getProperty(key);
	}
	
	public String getFieldName(String key){
		if(key.startsWith(prefix)){
			return key.replaceAll(prefix, ""); 
		}
		return key;
	}
	
	public String getFieldNameList(){
		ArrayList<Object> keys = Collections.list(props.keys());

		List<String> strKeys = new ArrayList<String>();
		for (Object object : keys) {
			if("prefix".equals(object)
				||"type".equals(object)){
				continue;
			}
			strKeys.add((String)object);
		}
		Collections.sort(strKeys);
		List<String> fields = new ArrayList<String>();
		for (String string : strKeys) {
			String field = getFieldName(string);
			if(string.startsWith(prefix)){
				fields.add(field);
			}
		}
		StringBuffer s = new StringBuffer();
		for (String field : fields) {
			s.append(field.toUpperCase()+",");
		}
		return s.substring(0,s.length()-1);
	}
	
	public String getParas(String key){
		String value = getProps().getProperty(key);
		if(value == null||value.length()==0){
			return "";
		}
		StringBuffer para = new StringBuffer();
		List<String> paras = new ArrayList<String>();
		char[] chars = value.toCharArray();
		int length = chars.length;
		for (int i=0;i<length;i++) {
			char c = chars[i];
			if(i+1<length&&i+2<length){
				char c1 = chars[i+1];
				char c2 = chars[i+2];
				if(c == '{'&&c2 == '}'){
					paras.add("String arg"+c1);
					i = i+2;
					continue;
				}
			}
			
		}
		
		if(paras.size()>0){
			for (String s : paras) {
				para.append(s+",");
			}
			return para.substring(0, para.length()-1);
		}
		return "";
	}
	
	public String getComFieldNames(){
		if("bill".equalsIgnoreCase(getType())){
			return "ID,CREATE_USER_ID,CREATE_TIME,MODIFY_USER_ID,MODIFY_TIME";
		}
		else if("oc".equalsIgnoreCase(getType())){
			return "ID,CORP_ID,CREATE_USER_ID,CREATE_TIME,MODIFY_USER_ID,MODIFY_TIME";
		}
		return "ID,CREATE_USER_ID,CREATE_TIME,MODIFY_USER_ID,MODIFY_TIME";
	}
}
